package com.ruoyi.system.service.module.estate.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.exception.TransactionalException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.PhoneUtils;
import com.ruoyi.system.domain.module.estate.*;
import com.ruoyi.system.domain.module.property.PropertyFeeOrderTemplate;
import com.ruoyi.system.mapper.module.estate.EstateMapper;
import com.ruoyi.system.mapper.module.estate.EstateRoomBangUserMapper;
import com.ruoyi.system.mapper.module.estate.EstateRoomMapper;
import com.ruoyi.system.mapper.module.property.PropertyFeeOrderTemplateMapper;
import com.ruoyi.system.service.module.ISmsTemplateService;
import com.ruoyi.system.service.module.estate.IEstateRoomService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;

/**
 * 小区内的房屋列信息Service业务层处理
 *
 * @author ruoyi
 * @date 2022-06-28
 */
@Service
public class EstateRoomServiceImpl extends ServiceImpl<EstateRoomMapper, EstateRoom> implements IEstateRoomService {

	@Resource
	private EstateRoomMapper estateRoomMapper;
	@Resource
	private EstateMapper estateMapper;
	@Resource
	private EstateRoomBangUserMapper estateRoomBangUserMapper;
	@Resource
	private PropertyFeeOrderTemplateMapper feeOrderTemplateMapper;
	@Resource
	private ISmsTemplateService smsTemplateService;

	@Override
	@Transactional
	public int updateRoom(EstateRoom estateRoom) {
		int ret = 0;
		try{
			ret = estateRoomMapper.updateById(estateRoom);
			if(ret <= 0){
				throw new TransactionalException("estateRoomMapper insert error");
			}

			//同步一下 数据模板里的  业主名称  手机号
			QueryWrapper<PropertyFeeOrderTemplate> qw = new QueryWrapper<>();
			qw.eq("room_id",estateRoom.getId());
			List<PropertyFeeOrderTemplate> templates = feeOrderTemplateMapper.selectList(qw);
			if(CollUtil.isNotEmpty(templates)){
				for (PropertyFeeOrderTemplate template : templates){
					template.setRealName(estateRoom.getRealName());
					template.setPhoneNum(estateRoom.getPhoneNum());

					//未交费的 修改房屋面积  和 物业费
					if(estateRoom.getIsHasDiffWyf() == 1 && template.getState() == 0){
						template.setRoomArea(Double.parseDouble(estateRoom.getRoomArea()));
						double totalPrice = Double.parseDouble(estateRoom.getRoomArea()) * template.getSinglePrice().doubleValue();
						template.setTotalPrice(new BigDecimal(totalPrice));
					}

					ret = feeOrderTemplateMapper.updateById(template);
					if(ret <= 0){
						throw new TransactionalException("feeOrderTemplateMapper insert error");
					}
				}
			}
			ret = 1;
		}catch (Exception e){
			e.printStackTrace();
			throw new TransactionalException("updateRoom insert error");
		}
		return ret;
	}

	@Override
	public int sendSmsByPropertyFeeToRoomUser(EstateRoom estateRoom) {
		Estate estate = estateMapper.selectById(estateRoom.getEstateId());
//		String telephone = estate.getTelphone();

		Map<String,Object> mapParam = new HashMap<>();
		mapParam.put("estateId", estateRoom.getEstateId());
		if(CollUtil.isNotEmpty(estateRoom.getRoomIds())){
			mapParam.put("roomIds", estateRoom.getRoomIds());
		}

		List<EstateRoom> unPayList = estateRoomMapper.selectUnPayRoomList(mapParam);
		for (EstateRoom room : unPayList){
			if(estateRoom.getUnPayMonthCount()!= null && estateRoom.getUnPayMonthCount() > 0){
				if(room.getUnPayMonthCount() >= estateRoom.getUnPayMonthCount()){
					List<String> phoneList = PhoneUtils.getPhoneListByStr(room.getPhoneNum());
					if(CollUtil.isNotEmpty(phoneList)){
						for (String phone : phoneList){
							System.out.println("电话号码：" + phone);
							//String year, String month1, String month2, BigDecimal money, String telephone
							smsTemplateService.sendSmsByPropertyFeeToRoomUser(phone, estateRoom,
								room.getUnPayYearNum(), room.getUnPayMonthNum(),
								DateUtils.getYear(),  DateUtils.getMonthTime(new Date()), room.getUnPayTotalMoney(), phone);
						}
					}
				}
			}else{
				List<String> phoneList = PhoneUtils.getPhoneListByStr(room.getPhoneNum());
				if(CollUtil.isNotEmpty(phoneList)){
					for (String phone : phoneList){
						System.out.println("电话号码：" + phone);
						//String year, String month1, String month2, BigDecimal money, String telephone
						smsTemplateService.sendSmsByPropertyFeeToRoomUser(phone, room,
							room.getUnPayYearNum(), room.getUnPayMonthNum(),
							DateUtils.getYear(),  DateUtils.getLastMonth(), room.getUnPayTotalMoney(), phone);
					}
				}
			}
		}
		return 1;
	}

	@Override
	public List<EstateRoom> getRoomListByUserId(int userId) {
		List<Integer> ids = new ArrayList<>();
		QueryWrapper<EstateRoomBangUser> qw = new QueryWrapper<>();
		qw.eq("bang_wx_user_id", userId);
		List<EstateRoomBangUser> roomIds = estateRoomBangUserMapper.selectList(qw);
		if(CollUtil.isNotEmpty(roomIds)){
			for (EstateRoomBangUser bangUser : roomIds){
				ids.add(bangUser.getRoomId());
			}
		}
		if(ids.size() > 0){
			QueryWrapper<EstateRoom> qwRoom = new QueryWrapper<>();
			qwRoom.in("id", ids);
			List<EstateRoom> rooms = estateRoomMapper.selectList(qwRoom);
			return rooms;
		}
		return null;
	}

	@Override
	public List<EstateBuild> getEstateBuildList(Integer estateId,Integer propertyId) {
		List<EstateBuild> list = new ArrayList<>();
		List<EstateRoom> roomList = estateRoomMapper.selectBuildList(estateId);
		if (roomList.size()>0){
			for (EstateRoom build : roomList){
				EstateBuild builds = new EstateBuild();
				builds.setEstateId(build.getEstateId());
				builds.setBuildNo(build.getBuildNo());
				builds.setBuildName(build.getBuildNo()+"号楼");
				builds.setParentId(0);
				builds.setBuildType(0);
				builds.setLevel(1);
				builds.setSort(list.size());
				builds.setState(1);
				builds.setPropertyId(propertyId);
				list.add(builds);
			}
		}
		return list;
	}

	@Override
	public List<EstateBuildUnit> getEstateBuildUnitList(String buildNo,Integer buildId,Integer estateId) {
		List<EstateBuildUnit> list = new ArrayList<>();
		Map<String,Object> map= new HashMap<>();
		map.put("buildNo",buildNo);
		map.put("estateId",estateId);
		List<EstateRoom> roomList = estateRoomMapper.selectBuildUnitList(map);
		if (roomList.size()>0){
			for (EstateRoom units:roomList){
				EstateBuildUnit unit = new EstateBuildUnit();
				unit.setEstateId(units.getEstateId());
				unit.setUnitNo(units.getUnitNo());
				unit.setSort(Integer.valueOf(units.getUnitNo()));
				unit.setBuildId(buildId);
				unit.setState(1);
				list.add(unit);
			}
		}
		return list;
	}

	@Override
	public List<EstateBuildFloor> getEstateBuildFloorList(String buildNo, String unitNo, Integer buildId, Integer unitId,Integer estateId,Integer propertyId) {
		List<EstateBuildFloor> list = new ArrayList<>();
		Map<String,Object> map= new HashMap<>();
		map.put("buildNo",buildNo);
		map.put("unitNo",unitNo);
		map.put("estateId",estateId);
		List<EstateRoom> roomList = estateRoomMapper.selectBuildFloorList(map);
		if (roomList.size()>0){
			for (EstateRoom room : roomList){
				EstateBuildFloor floor = new EstateBuildFloor();
				if (room.getRoomNum().length()==3){
					floor.setFloorNum(room.getRoomNum().substring(0,1));
					floor.setSort(Integer.valueOf(room.getRoomNum().substring(0,1)));
					floor.setFloorName("第"+room.getRoomNum().substring(0,1)+"层");
				}else {
					floor.setFloorNum(room.getRoomNum().substring(0,2));
					floor.setSort(Integer.valueOf(room.getRoomNum().substring(0,2)));
					floor.setFloorName("第"+room.getRoomNum().substring(0,2)+"层");
				}
				floor.setBuildId(buildId);
				floor.setUnitId(unitId);
				floor.setState(1);
				if (list.size()>0){
					int p = 1;
					for (EstateBuildFloor floor1 : list){
						if (floor1.getFloorNum().equals(floor.getFloorNum())){
							p=0;
						};
					}
					if (p==1){
						list.add(floor);
					}
				}else {
					list.add(floor);
				}
			}
		}
		return list;
	}
}
